import React, { useEffect, useState } from 'react'
import { Card, Button, Table, message, Modal, Form, Input, Tree } from 'antd'
import { PlusCircleOutlined } from '@ant-design/icons'
import dayjs from 'dayjs'
import { useSelector, shallowEqual } from 'react-redux'
import ajax from '../../service/ajax'
import treeData from '../../config/tree_config'
const { Item } = Form

export default function Role() {

  const [roleList, setRoleList] = useState([])
  const [visibleAdd, setVisibleAdd] = useState(false);
  const [visibleAuth, setvisibleAuth] = useState(false)
  const [roleId, setRoleId] = useState()
  const [checks, setChecks] = useState([])
  const [form] = Form.useForm()

  const { username } = useSelector((state) => ({
    username: state.userInfo.user.username
  }), shallowEqual)

  const columns = [
    {
      title: '角色名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      key: 'create_time',
      render: (create_time) => dayjs(create_time).format('YYYY年 MM月DD日 HH:mm:ss')
    },
    {
      title: '授权时间',
      dataIndex: 'auth_time',
      key: 'auth_time',
      render: (auth_time) => auth_time ? dayjs(auth_time).format('YYYY年 MM月DD日 HH:mm:ss') : '暂未授权'
    },
    {
      title: '授权人',
      dataIndex: 'auth_name',
      key: 'auth_name',
      render: (auth_name) => auth_name ? auth_name : '暂未授权'
    },
    {
      title: '操作',
      dataIndex: '_id',
      key: '_id',
      align: 'center',
      width: '10%',
      render: (id) => <Button onClick={() => showModal(id)} type="link">设置权限</Button>
    }
  ];

  useEffect(() => {
    getRoleList()
  }, [])

  const showModal = (id) => {
    setvisibleAuth(true)
    setRoleId(id)
   
     roleList.forEach((roleObj)=>{
      if(roleObj._id === id){
        if(roleObj.menus.indexOf('home') === -1){
          roleObj.menus.push('home')
        }
        setChecks(roleObj.menus)
      }
    })
  }

  const getRoleList = async () => {
    let { status, data, msg } = await ajax('/manage/user/list')
    if (status === 0) {
      setRoleList(data.roles.reverse())
    } else {
      message.error(msg)
    }
  }

  const addRole = async () => {
    let roleName = form.getFieldValue().roleName
    let { status, msg } = await ajax.post('/manage/role/add', { roleName })
    if (status === 0) {
      message.success('添加角色成功')
      getRoleList()
      form.resetFields()
    } else {
      message.error(msg)
    }
    setVisibleAdd(false)
  }

  const handleAddCancel = () => {
    setVisibleAdd(false)
    form.resetFields()
  };

  const setAuth = async() => {
    let { status, msg } = await ajax.post('/manage/role/update', { _id: roleId, menus: checks, auth_time: Date.now(), auth_name: username })
    if (status === 0) {
      message.success('授权成功')
      getRoleList()
    } else {
      message.error(msg)
    }
    setvisibleAuth(false)
  }

  const onChecked = (checkArr) => {
    setChecks(checkArr)
  }

  return (
    <div>
      <Card
        title={
          <div>
            <Button type="primary" onClick={() => setVisibleAdd(true)}>
              <PlusCircleOutlined />
            新增角色
          </Button>
          </div>
        }
      >
        <Table
          dataSource={roleList}
          columns={columns}
          bordered
          rowKey="_id"
        />
      </Card>
      <Modal
        title="新增角色"
        okText="确认"
        cancelText="取消"
        onOk={() => addRole()}
        onCancel={() => handleAddCancel()}
        visible={visibleAdd}
      >
        <Form
          form={form}
        >
          <Item
            name="roleName"
            rules={[
              { required: true, message: '角色名不能为空' }
            ]}
          >
            <Input placeholder="请输入角色名" />
          </Item>
        </Form>
      </Modal>

      <Modal
        title="设置权限"
        okText="确认"
        cancelText="取消"
        onOk={() => setAuth()}
        onCancel={() => setvisibleAuth(false)}
        visible={visibleAuth}
      >
        <Tree
          treeData={treeData}
          defaultExpandAll
          checkable
          checkedKeys={checks}
          onCheck={(checkArr) => onChecked(checkArr)}
        />
      </Modal>
    </div>
  )
}